//
//  PMSideStatisticsViewController.m
//  ERP
//
//  Created by QA on 15/12/24.
//  Copyright © 2015年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "PMSideStatisticsViewController.h"
//#import "MJRefresh.h"
#import "PMSideStatisticsViewCell.h"
#import "PMSideStatisticsHeaderViewCell.h"
#import "UITableView+Custom.h"

#import "WebServiceCommonRequest.h"
#import "AbstractNavigationController.h"

#import "NSKeyedArchiverUserLogin.h"
#import "NSDictionary+DataFormat.h"
#import "PMSideStatisticsDetailViewController.h"
#import "PMSideStatisticsSearchViewController.h"

#import "GEDateFromatter.h"
#import "GEWeekTimeFromatter.h"

@interface PMSideStatisticsViewController ()

@property (strong, nonatomic) NSMutableArray *resultData;
@property (strong, nonatomic) NSMutableArray *cellRowData;

@property (assign, nonatomic) NSInteger stateContentState;
@property (assign, nonatomic) NSInteger segmentActionState;
@property (assign, nonatomic) BOOL isExpand;

@end

@implementation PMSideStatisticsViewController
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self setTitle: @"站点砼方量"];
        [self addSearchToNavigationItem];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData = [NSMutableArray array];
    self.cellRowData = [NSMutableArray array];
    
    self.tableView.tableHeaderView= self.tableHeaderView;
    self.tableView.tableFooterView= [[UIView alloc] init];
    
    [self.tableView registerClass:[PMSideStatisticsHeaderViewCell class] forCellReuseIdentifier:@"PMSideStatisticsHeaderViewCell"];
    [self.tableView registerClass:[PMSideStatisticsViewCell class] forCellReuseIdentifier:@"PMSideStatisticsViewCell"];
    
    //获取时间数据
    //NSString *time = [GEDateFromatter formmatTimeDate:[NSDate date] format:@"yyyy-MM"];
    //self.startTime = [NSString stringWithFormat:@"%@-01",time];
    //self.endTime = [GEDateFromatter formmatTimeDate:[NSDate date]];
    [self getNetWorkDataStartTime:self.startTime endTime:self.endTime];
}

//获取上一个页面传递的参数
- (void)getPassingParameter:(id)object
{
    if(!object) return;
    NSDictionary *mDictionary = object;
    NSString *stationName = [mDictionary objectFormatStringForKey:@"站点名称"];
    self.stationID = [mDictionary objectFormatIntegerForKey:@"站点ID"];
    [self setStationName:stationName StationID:self.stationID];
    
    self.startTime = [mDictionary objectFormatStringForKey:@"开始时间"];
    self.endTime = [mDictionary objectFormatStringForKey:@"截止日期"];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat yOffset  = scrollView.contentOffset.y;
    
    if (yOffset < 0) {
        CGRect f = self.headerBgView.frame;
        f.origin.y = yOffset;
        f.size.height = -yOffset + self.tableHeaderView.bounds.size.height;
        self.headerBgView.frame = f;
    }
}

#pragma mark 网络日期获取数据
- (void)getNetWorkDataStartTime:(NSString*)startTime endTime:(NSString*)endTime
{
    self.fhfl.text = @"0.0";
    self.qsfl.text = @"0.0";
    [self.resultData removeAllObjects];
    [self.cellRowData removeAllObjects];
    
    NSString *startTimeS = [startTime stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    NSString *endTimeS = [endTime stringByReplacingOccurrencesOfString:@"-" withString:@"."];
    self.updateTime.text = [NSString stringWithFormat:@"数据同步于%@至%@",startTimeS, endTimeS];
    
    self.segmentActionState = -1;
    self.isExpand = NO;
    self.stateContentState = 0;
    [self.tableView showCustomProgressOffset:80];
    
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"SCDD_TFLTJ_REPORT_20160112"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content addParameterKey:@"开始日期" value:startTime];
    [content addParameterKey:@"截止日期" value:endTime];
    //设置站点ID
    [content setStationID:self.stationID];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self.tableView hideProgress];
        
        //总数量显示设置
        if(result.resultArray && result.resultArray.count>0){
            NSArray *firstArray = [result.resultArray firstObject];
            
            if(firstArray && firstArray.count>0){
                NSDictionary *mDictionary = [firstArray firstObject];
                CGFloat scValue = 0;
                CGFloat qsValue = 0;
                scValue = [mDictionary objectFormatFloatForKey:@"生产方量" retain:1 except:1];
                qsValue = [mDictionary objectFormatFloatForKey:@"签收方量" retain:1 except:1];
                self.scfl.text = [NSString stringWithFormat:@"%0.1f",scValue];
                self.qsfl.text = [NSString stringWithFormat:@"%0.1f",qsValue];
                self.fhfl.text = [mDictionary objectFormatFloatStringForKey:@"发货方量" retain:1 format:@"%@"];
                CGFloat ylValue = qsValue - scValue;
                self.ylfl.text = [NSString stringWithFormat:@"%0.1f",ylValue];
            }
        }
        
        //添加数据，刷新页面
        NSArray *lastArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            lastArray = [result.resultArray lastObject];
        
        if(lastArray && lastArray.count>0){
            [self.resultData removeAllObjects];
            [self.resultData addObjectsFromArray:lastArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            [self.tableView reloadData];
        } else {
            [self.tableView setTableViewNotDataDrawText:@"暂无数据" isShow:YES];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"无法连接网络"];
    }];
}

- (void)errorInfoViewText:(NSString*)label
{
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}


#pragma mark 网络获取数据

- (void)getNetWorkDataTime:(NSString*)timeString
{
    self.stateContentState = 0;
    
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"SCDD_TFLTJ_REPORT_LIST_20171012"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content setStationID:self.stationID];
    [content addParameterKey:@"日期" value:timeString];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self.tableView hideProgress];
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        if(result.resultArray && result.resultArray.count>0)
            firstArray = [result.resultArray firstObject];
        
        if(firstArray && firstArray.count>0){
            [self.cellRowData removeAllObjects];
            [self.cellRowData addObjectsFromArray:firstArray];
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            self.stateContentState = 3;
            [self.tableView reloadData];
        } else {
            self.stateContentState = 1;
            [self.tableView reloadData];
        }
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.stateContentState = 2;
        [self.tableView reloadData];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        self.stateContentState = 2;
        [self.tableView reloadData];
    }];
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.resultData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == _segmentActionState) {
        if(_cellRowData.count > 0) return _cellRowData.count;
        else if(self.isExpand) return 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_cellRowData.count > 0){
        PMSideStatisticsViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PMSideStatisticsViewCell"];
        
        NSDictionary *itemData = [self.cellRowData objectAtIndex:indexPath.row];
        cell.gcmcLabel.text = [itemData objectFormatStringForKey:@"工程名称" defaults:@"未知"];
        cell.rwdbhLabel.text = [itemData objectFormatStringForKey:@"任务单编号" defaults:@"未知"];
        cell.khmcLabel.text = [itemData objectFormatStringForKey:@"客户名称" defaults:@"未知"];
        cell.sgbwLabel.text = [itemData objectFormatStringForKey:@"施工部位" defaults:@"未知"];
        cell.scLabel.text = [itemData objectFormatFloatStringForKey:@"生产方量" retain:1 format:@"%@方"];
        cell.fhLabel.text = [itemData objectFormatFloatStringForKey:@"发货方量" retain:1 format:@"%@方"];
        cell.qsLabel.text = [itemData objectFormatFloatStringForKey:@"客户签收量" retain:1 format:@"%@方"];
        
        return cell;
    } else {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ActivityIndicat"];
        cell.contentView.frame = CGRectMake(0, 0, SuperWidth, 55);
        
        if(self.stateContentState == 0) {//加载进度条
            UIActivityIndicatorView *act=[[UIActivityIndicatorView  alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
            act.center = CGPointMake(SuperWidth/2, 26.5);
            act.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
            act.hidesWhenStopped = YES;
            [act startAnimating];
            [cell.contentView addSubview:act];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        } else if(self.stateContentState == 1){//显示无数据提示
            UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
            label.text = @"没有任务单";
            label.font = [UIFont fontWithName:@"Arial" size:16];
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:label];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        } else if(self.stateContentState == 2){//显示失败提示
            UILabel* label = [[UILabel alloc] initWithFrame:cell.contentView.frame];
            label.text = @"加载数据失败";
            label.font = [UIFont fontWithName:@"Arial" size:16];
            label.textColor = [UIColor lightGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [cell.contentView addSubview:label];
            return cell;
        }
        return cell;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    PMSideStatisticsHeaderViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PMSideStatisticsHeaderViewCell"];
    cell.button.tag = section;
    [cell.button addTarget:self action:@selector(tapHeader:) forControlEvents:UIControlEventTouchUpInside];
    
    NSDictionary *itemData = [self.resultData objectAtIndex:section];
    NSString *timeString = [itemData objectFormatStringForKey:@"日期" defaults:@"1900-00-00"];
    NSArray *array = [timeString componentsSeparatedByString:@"-"];
    
    cell.timeLabel.text = array.count>2 ? [NSString stringWithFormat:@"%@日", array[2]] : @"00日";
    cell.monthLabel.text = array.count>2 ? [NSString stringWithFormat:@"%@-%@月", array[0],array[1]] : @"1900-01月";
    cell.fhlLabel.text = [itemData objectFormatFloatStringForKey:@"发货方量" retain:1 format:@"%@"];
    CGFloat sclValue = 0;
    CGFloat qslValue = 0;
    sclValue = [itemData objectFormatFloatForKey:@"生产方量" retain:1 except:1];
    qslValue = [itemData objectFormatFloatForKey:@"签收方量" retain:1 except:1];
    cell.qslLabel.text = [NSString stringWithFormat:@"%0.1f",qslValue];
    cell.sclLabel.text = [NSString stringWithFormat:@"%0.1f",sclValue];
    CGFloat yllValue = qslValue - sclValue;
    cell.yllLabel.text =[NSString stringWithFormat:@"%0.1f",yllValue];
    return cell.contentView;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 52;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_cellRowData.count > 0) return 86;
    else return 55;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.stateContentState == 3) {
        NSDictionary *itemData = [self.cellRowData objectAtIndex:indexPath.row];
        PMSideStatisticsDetailViewController *viewController = [[PMSideStatisticsDetailViewController alloc] initWithValue:itemData];
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

#pragma mark -
#pragma mark IBAction

- (void)searchChargeSelector:(id)sender
{
    PMSideStatisticsSearchViewController *view = [[PMSideStatisticsSearchViewController alloc] init];
    view.backResultDelagate = self;
    AbstractNavigationController *navigation = [[AbstractNavigationController alloc] initWithRootViewController:view];
    [self.navigationController presentViewController:navigation animated:NO completion:nil];
}

#pragma mark - Other Method
//点击header的方法
-(void)tapHeader:(UIButton *)sender
{
    NSInteger section = sender.tag;
    NSDictionary *mDictionary = [self.resultData objectAtIndex:section];
    NSString *timeString = [mDictionary objectFormatStringForKey:@"日期" defaults:@"1900-00-00"];

    if(self.isExpand && self.segmentActionState != section){
        self.isExpand = YES;
        [self.cellRowData removeAllObjects];
        //添加新节点
        [self getNetWorkDataTime:timeString];
        
    } else if(self.isExpand){
        self.isExpand = NO;
        [self.cellRowData removeAllObjects];
        
    } else {
        self.isExpand = YES;
        //添加新节点
        [self getNetWorkDataTime:timeString];
    }
    
    self.segmentActionState = section;
    [self.tableView reloadData];
}

#pragma mark - Other Method

- (void)backResultDataKey:(id)key dataValue:(id)backValue
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    if (!backValue) return;
    
    NSArray *array = backValue;
    self.startTime = array[0];
    self.endTime = array[1];
    
    //获取时间数据
    [self getNetWorkDataStartTime:array[0] endTime:array[1]];
}

@end
